package wjh.utils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.web.servlet.ModelAndView;
import wjh.config.AlipayConfig;
import wjh.pojo.Notice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public class AlipayUtil {
    public static String confirmPayment(String report_number, String money, String orderName, String desc, HttpServletResponse response){
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.GATEWAY_URL, AlipayConfig.APP_ID, AlipayConfig.MERCHANT_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGN_TYPE);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.RETURN_URL);
        alipayRequest.setNotifyUrl(AlipayConfig.NOTIFY_URL);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = report_number;
        //付款金额，必填
        String total_amount = money;
        //订单名称，必填
        String subject = orderName;
        //商品描述，可空
        String body = desc;
        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "1c";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\"" + timeout_express + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String url = "";
        try {
            url = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
            response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
            response.getWriter().write(url); // 直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();

        } catch (AlipayApiException | IOException e) {
            e.printStackTrace();
        }
        System.out.println(url);
        return url;
    }
    public static Notice checkSign(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        Notice notice = new Notice();
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes(AlipayConfig.CHARSET_), AlipayConfig.CHARSET);
            params.put(name, valueStr);
        }
        //调用SDK验证签名
        notice.setSignVerified(AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGN_TYPE));
        notice.setModelAndView(new ModelAndView("succ"));
        //商户订单号
        notice.setOutTradeNo(new String(request.getParameter("out_trade_no").getBytes(AlipayConfig.CHARSET_), AlipayConfig.CHARSET));
        //支付宝交易号
        notice.setTradeNo(new String(request.getParameter("trade_no").getBytes(AlipayConfig.CHARSET_), AlipayConfig.CHARSET));
        //付款金额
        notice.setTradeAmount(new String(request.getParameter("total_amount").getBytes(AlipayConfig.CHARSET_), AlipayConfig.CHARSET));
        //交易状态
//        notice.setTradeStatus(new String(request.getParameter("trade_status").getBytes(AlipayConfig.CHARSET_), AlipayConfig.CHARSET_);
        return notice;
    }

    public static Notice checkSign2(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        Notice notice2 = new Notice();
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes(AlipayConfig.CHARSET_), AlipayConfig.CHARSET);
            params.put(name, valueStr);
        }
        //调用SDK验证签名
        notice2.setSignVerified(AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGN_TYPE));
        notice2.setModelAndView(new ModelAndView("succ2"));
        //商户订单号
        notice2.setOutTradeNo(new String(request.getParameter("out_trade_no").getBytes(AlipayConfig.CHARSET_), AlipayConfig.CHARSET));
        //支付宝交易号
        notice2.setTradeNo(new String(request.getParameter("trade_no").getBytes(AlipayConfig.CHARSET_), AlipayConfig.CHARSET));
        //付款金额
        notice2.setTradeAmount(new String(request.getParameter("total_amount").getBytes(AlipayConfig.CHARSET_), AlipayConfig.CHARSET));
        //交易状态
        // notice2.setTradeStatus(new String(request.getParameter("trade_status").getBytes(AlipayConfig.CHARSET_), AlipayConfig.CHARSET));
        return notice2;
    }

}
